//
//  TransitionToDetailVC.m
//  Btpin
//
//  Created by Vic on 2019/12/14.
//  Copyright © 2019 Vic. All rights reserved.
//

#import "TransitionToDetailVC.h"
#import "JobCollectionViewCell.h"
#import "PersonalHomeViewController.h"
#import "JobDetailViewController.h"

@implementation TransitionToDetailVC

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    PersonalHomeViewController *fromVC = (PersonalHomeViewController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    JobDetailViewController *toVC = (JobDetailViewController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *containerView = [transitionContext containerView];
    NSTimeInterval duration = [self transitionDuration:transitionContext];
    
    JobCollectionViewCell *cell = (JobCollectionViewCell *)[fromVC.cCollectionView cellForItemAtIndexPath:fromVC.selectedIndexPath];
    UIView *cellBgView = [cell.bgView snapshotViewAfterScreenUpdates:NO];
    
    cellBgView.frame = [containerView convertRect:cell.bgView.frame fromView:cell.bgView.superview];
    cell.bgView.hidden = YES;
    toVC.view.frame = [transitionContext finalFrameForViewController:toVC];
    toVC.view.alpha = 0;
    [containerView insertSubview:toVC.view belowSubview:fromVC.view];
    [containerView addSubview:cellBgView];
    
    JobCollectionViewCell *detailCell = (JobCollectionViewCell *)[toVC.jobTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    detailCell = [[JobCollectionViewCell alloc] initWithFrame:CGRectMake(0, HeightOfStatusBarAndNavigationBar, WIDTH, 50)];
    detailCell.bgView.hidden = YES;
    detailCell.bgView = [UIToolsControl initViewWithFrame:CGRectMake(0, 0, WIDTH, 50) backgroundColor:COLOR_OF_CLEAR];
    
    [UIView animateWithDuration:duration animations:^{
        fromVC.cCollectionView.alpha = 0.0;
        toVC.view.alpha = 1;
        cellBgView.frame = [containerView convertRect:detailCell.bgView.frame fromView:detailCell.bgView.superview];
    } completion:^(BOOL finished) {
        [cellBgView removeFromSuperview];
        detailCell.bgView.hidden = NO;
        cell.bgView.hidden = NO;
        [transitionContext completeTransition:!transitionContext.transitionWasCancelled];
    }];
}

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return 0.4;
}

@end
